package com.edu.common.utils.http;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import lombok.extern.slf4j.Slf4j;

/**
 * @author huangc
 *
 */
@Slf4j
@Component
public class HttpClientX {

	@Autowired
	private RestTemplate restTemplate;

	public String post(String url, Map<String, String> header, Map<String, Object> params) {

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		if (null != header) {
			for (String key : header.keySet()) {
				headers.add(key, header.get(key));
			}
		}

		MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
		if (null != params) {
			for (String key : params.keySet()) {
				body.add(key, params.get(key));
			}
		}

		HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(body, headers);
		String res = restTemplate.postForObject(url, httpEntity, String.class);
		if (log.isDebugEnabled()) {
			log.debug(res);
		}
		return res;
	}

}
